package com.test.selenium;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @Author lizhilong
 * @create 2020/1/7 18:16
 * @desc 使用 phantomJs 爬取东方财富亚洲股市指数。使用webmagic 集成selenium
 */
public class EastmoneyProcessor implements PageProcessor {

    private Site site = Site.me().setCycleRetryTimes(5).setRetryTimes(5).setSleepTime(500).setTimeOut(3 * 60 * 1000)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0")
            .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
            .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
            .setCharset("UTF-8");

    @Override
    public void process(Page page) {
        PhantomJSDriver webDriver = MyPhanTomJsDriver.getWebDriver();
        webDriver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        webDriver.get(page.getRequest().getUrl());
        String pageSource = webDriver.getPageSource();
        MyPhanTomJsDriver.close();
        Document document = Jsoup.parse(pageSource);
        Elements elements = document.select("table").select("tr");
        StringBuffer buffer = new StringBuffer();
        elements.forEach(new Consumer<Element>() {
            @Override
            public void accept(Element element) {
                Elements tds = element.select("td");
                tds.forEach(new Consumer<Element>() {
                    @Override
                    public void accept(Element td) {
                        buffer.append(td.text()).append("||");
                    }
                });
                System.out.println(buffer.toString());
                buffer.delete(0,buffer.length());
            }
        });
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider eastMoneySpider = Spider.create(new EastmoneyProcessor()).addUrl("http://quote.eastmoney.com/center/gridlist.html#global_asia")
                .thread(5)
                .setExitWhenComplete(true);
        eastMoneySpider.start();
        eastMoneySpider.stop();
    }
}
